package leetcode.f1t100;

import java.util.regex.Pattern;

/**
 * 判断是否数字, 包含正负及科学计数法
 * https://leetcode.com/problems/valid-number/
 *
 * @Author lichongxiao
 * @Date 2022/10/25 17:28
 */
public class Q65_ValidNumber {
    public boolean isNumber(String s) {
//        return validNumber(s);
        char[] chars = s.toCharArray();
        boolean eflag = false, pointFlag = false, numberFlag = false, eIntegerFlag = true;
        for (int i = 0,length=chars.length; i < length; i++) {
            if(chars[i] == '+' || chars[i] == '-'){
                if(i != 0 && (chars[i-1] != 'e' && chars[i-1] != 'E')){
                    return false;
                }
            }else if(chars[i] == '.'){
                if(eflag || pointFlag){
                    return false;
                }
                pointFlag = true;
            } else if(chars[i] == 'e' || chars[i] == 'E'){
                if(eflag || !numberFlag){
                    return false;
                }
                eflag = true;
                eIntegerFlag = false;
            } else if(chars[i]>= '0' && chars[i] <= '9'){
                numberFlag = true;
                eIntegerFlag = true;
            }else{
                return false;
            }
        }
        return numberFlag && eIntegerFlag;
    }



    private boolean validInteger(String s) {
        return Pattern.matches("[\\+,-]?\\d+", s);
    }

    private boolean validNumber(String s) {
        String[] split = s.split("[e,E]",-1);
        if(split.length == 1){
            return validInteger(s) || validDecimalNumber(s);
        } else if(split.length != 2){
            return false;
        }
        return (validInteger(split[0]) || validDecimalNumber(split[0])) && validInteger(split[1]);

    }

    private boolean validDecimalNumber(String s) {
        return Pattern.matches("[\\+,-]?\\d+[\\.]?\\d*", s)
                ||Pattern.matches("[\\+,-]?\\d*[\\.]?\\d+", s);
    }

    public static void main(String[] args) {

        Q65_ValidNumber bean = new Q65_ValidNumber();
//        String[] strs = new String[] {"2", "0089", "-0.1", "+3.14", "4.", "-.9", "2e10", "-90E3", "3e+7", "+6e-1", "53.5e93", "-123.456e789","005047e+6"};
        String[] strs = new String[] {"005047e+6"};
//        String[] strs = new String[] {"abc", "1a", "1e", "e3", "99e2.5", "--6", "-+3", "95a54e53"};
        for(String str : strs){
            System.out.println(bean.isNumber(str));
        }

    }
}
